#!/bin/sh /etc/rc.common
# Copyright (C) 2018-2020 Lienol <lawlienol@gmail.com>

START=99

CONFIG=ssr_libev_server
CONFIG_PATH=/var/etc/$CONFIG

add_rule() {
	iptables -N SSR_LIBEV-SERVER
	iptables -I INPUT -j SSR_LIBEV-SERVER
}

del_rule() {
	iptables -D INPUT -j SSR_LIBEV-SERVER 2>/dev/null
	iptables -F SSR_LIBEV-SERVER 2>/dev/null
	iptables -X SSR_LIBEV-SERVER 2>/dev/null
}

gen_include() {
	echo '#!/bin/sh' > /var/etc/$CONFIG.include
	extract_rules() {
		echo "*$1"
		iptables-save -t $1 | grep "SSR_LIBEV-SERVER" | \
		sed -e "s/^-A \(INPUT\)/-I \1 1/"
		echo 'COMMIT'
	}
	cat <<-EOF >> /var/etc/$CONFIG.include
		iptables-save -c | grep -v "SSR_LIBEV-SERVER" | iptables-restore -c
		iptables-restore -n <<-EOT
		$(extract_rules filter)
		EOT
	EOF
	return 0
}

gen_ssr_libev_config_file() {
	config_get enable $1 enable
	[ "$enable" = "0" ] && return 0
	config_get remarks $1 remarks
	config_get port $1 port
	config_get password $1 password
	config_get method $1 method
	config_get protocol $1 protocol
	config_get protocol_param $1 protocol_param
	config_get obfs $1 obfs
	config_get obfs_param $1 obfs_param
	config_get timeout $1 timeout
	config_get fast_open $1 fast_open
	config_get udp_forward $1 udp_forward
	udp_param=""
	[ "$udp_forward" = "1" ] && udp_param="-u"
	
	cat <<-EOF >$CONFIG_PATH/$1.json
		{
		    "server": ["[::0]", "0.0.0.0"],
		    "server_port": $port,
		    "password": "$password",
		    "timeout": $timeout,
		    "method": "$method",
		    "protocol": "$protocol",
		    "protocol_param": "$protocol_param",
		    "obfs": "$obfs",
		    "obfs_param": "$obfs_param",
		    "fast_open": $fast_open
		}
		EOF
		
	/usr/bin/ssr-server -c $CONFIG_PATH/$1.json $udp_param >/dev/null 2>&1 &
	iptables -A SSR_LIBEV-SERVER -p tcp --dport $port -m comment --comment "$remarks" -j ACCEPT
	[ "$udp_forward" = "1" ] && iptables -A SSR_LIBEV-SERVER -p udp --dport $port -m comment --comment "$remarks" -j ACCEPT
}

start_ssr_libev_server() {
	add_rule
	config_load $CONFIG
	config_foreach gen_ssr_libev_config_file "user"
	gen_include
}

stop_ssr_libev_server() {
	ps -w | grep "$CONFIG_PATH/" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	del_rule
	rm -rf $CONFIG_PATH /var/etc/$CONFIG.include
}

start() {
	enable=$(uci -q get $CONFIG.@global[0].enable)
	if [ "$enable" = "0" ];then
		stop_ssr_libev_server
	else
		mkdir -p $CONFIG_PATH
		start_ssr_libev_server
	fi
}

stop() {
	stop_ssr_libev_server
}

restart() {
	stop
	start
}